package com.boot.springboot.service;




import com.boot.springboot.pojo.PendingShipment;
import com.boot.springboot.pojo.dto.PendingShipmentDto;
import com.boot.springboot.repository.PendingShipmentRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.awt.geom.GeneralPath;
import java.util.List;
import java.util.Optional;

@Service //spring的bean
public class PendingShipmentService implements IPendingShipmentService {
    @Autowired //自动装配
    PendingShipmentRepository pendingShipmentRepository;
    @Override
    public PendingShipment add(PendingShipmentDto pendingShipment) {
        PendingShipment pendingShipmentPojo=new PendingShipment();
        BeanUtils.copyProperties(pendingShipment,pendingShipmentPojo);
        if (pendingShipmentRepository.findByGoodId(pendingShipmentPojo.getGoodId()).isPresent()) {
            throw new IllegalArgumentException("商品ID已存在：" + pendingShipmentPojo.getGoodId());
        }
        return pendingShipmentRepository.save(pendingShipmentPojo);

    }

    @Override
    public PendingShipment get(Integer goodId) {
        return pendingShipmentRepository.findByGoodId(goodId).orElseThrow(() -> {
            throw new IllegalArgumentException("不存在该商品，异常参数");
        });


    }

    @Override
    public  PendingShipment edit(PendingShipmentDto pendingShipment) {
        //先查询数据库中已存在的商品（通过goodId）
        PendingShipment pendingShipmentPojo= pendingShipmentRepository.findByGoodId(pendingShipment.getGoodId())
                .orElseThrow(() -> new IllegalArgumentException("商品不存在：" + pendingShipment.getGoodId()));
        BeanUtils.copyProperties(pendingShipment,pendingShipmentPojo);
        return pendingShipmentRepository.save(pendingShipmentPojo);
    }

    @Transactional//JPA允许get方法通过非主键来进行查询，但detele不允许，所以为delete 方法开启一个数据库事务
    @Override
    public void delete(Integer goodId) {
        PendingShipment pendingShipment = pendingShipmentRepository.findByGoodId(goodId).orElseThrow(() -> new IllegalArgumentException("商品不存在，goodId：" + goodId));
        pendingShipmentRepository.deleteByGoodId(goodId);
    }

    @Override
    public List<PendingShipment> getAllPendingShipments() {
        return (List<PendingShipment>) pendingShipmentRepository.findAll();
    }
}
